<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use GuzzleHttp;
use App\User;
use Illuminate\Support\Facades\Auth;

class WechatController extends Controller
{
    protected $client;
    public function __construct()
    {
        $this->client = new GuzzleHttp\Client();

    }

    public function validateWechatToken(Request $request)
    {
        $echoStr = $request->input('echostr');
        $signature = $request->input('signature');
        $timestamp = $request->input('timestamp');
        $nonce = $request->input('nonce');

        $token = 'juudddee8727474';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return $echoStr;
        }
    }


    public function wechatLoginCallback(Request $request) {
        //https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx41cb8dbd827a16e9&secret=d4624c36b6795d1d99dcf0547af5443d&code=00137323023ab55775be09d6d8e75ffA&grant_type=authorization_code
        //获取token和用户id
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $code = $request->input('code');
        $appid = '?appid=wxa585c7f09efe3ec0';
        $secret = '&secret=582c1f8af7498419793b10ce892fda8c';
        $code = '&code='.$code;
        $grand_type = '&grant_type=authorization_code';
        $url = $url.$appid.$secret.$code.$grand_type;
        $res = $this->client->request('GET', $url);

        $wechatJson = GuzzleHttp\json_decode( $res->getBody());

        $wechat_openid = $wechatJson->openid;
        $wechat_token = $wechatJson->access_token;

        $wechatUser = User::firstOrNew(compact('wechat_openid'));

        if($wechatUser->id && !empty($wechatUser->phone)) {
            Auth::login($wechatUser);
            return redirect(url('agent'));
        }

        $wechatUser->wechat_token = $wechat_token;
        //更具token和openid 获取用户信息
        //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        $userUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$wechat_token.'&openid='.$wechat_openid;
        $res = $this->client->request('GET', $userUrl);
        $userJson = GuzzleHttp\json_decode( $res->getBody());
        //创建用户
        $wechatUser->name = $userJson->nickname;
        $wechatUser->wechat_name = $userJson->nickname;
        $wechatUser->gender = $userJson->sex == 1 ? '男' : '女';
        $wechatUser->wechat_avatar = $userJson->headimgurl;
        $wechatUser->save();
        //授权用户登陆
        Auth::login($wechatUser);

        return redirect(url('reg'));
    }
}
